<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entity_Category_Cache {

	public function isValid() {
		return App::config()->get('cache_valid');
	}
	
	public function refresh() {
		$childs = array();
		$this->_cats = App::db()->query('select * from category')->result_array();
		foreach($this->_cats as $cat)
			$childs[$cat['id']] = $this->getChild($cat['id']);

		$v = '';
		foreach($childs as $ancestor => $descendants) {
			foreach($descendants as $descendant) {
				$v .= "($ancestor, $descendant), ";
			}
		}
		$v = rtrim($v, ', ');
		App::db()->query("DELETE FROM cat_index");
		App::db()->query("INSERT INTO cat_index(ancestor, descendant) VALUES $v");
		$this->setIsValid(true);
	}
	
	public function setIsValid($valid) {
		return App::config()->set('cache_valid', (int)$valid);
	}

	protected $_getChild = array();
	
	protected $_getParent = array();

	protected $_cats = array();
	
	private function getChild($id) {
		if (!isset($this->_getChild[$id])) {
			$res = array($id);
			foreach($this->_cats as $cat) {
				if ($cat['parent_category'] == $id)
					$res = array_merge($res, $this->getChild($cat['id']));
			}
			$this->_getChild[$id] = $res;
		}
		return $this->_getChild[$id];
	}
	
	private function getParent($id) {
		if (!isset($this->_getParent[$id])) {
			$res = null;
			foreach($this->_cats as $cat) {
				if ($cat['id'] == $id)
					$res = $cat['parent_category'];
			}
			$this->_getParent[$id] = $res;
		}
		return $this->_getParent[$id];
	}
}